package listbyorder.access001_100.test39;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/5/31 10:45
 */
public class Solution1 {

    // 方法一： 经典的回溯算法
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(0, res, candidates, target, new ArrayList<>(), 0);
        return res;
    }

    private void dfs(int s, List<List<Integer>> res, int[] candidates, int target, ArrayList<Integer> path, int sum) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        if (sum > target || s == candidates.length) {
            return;
        }
        for (int i = s; i < candidates.length; i++) {
            path.add(candidates[i]);
            dfs(i, res, candidates, target, path, sum + candidates[i]);
            path.remove(path.size() - 1);
        }
    }
}
